var conf = require("../conf.json");
var http = require('http');
var qs = require("querystring");
var path = require('path');
var basedir = path.resolve(__dirname, "..");
var source = path.resolve(__dirname);

function process(req, res, db) {
    var finish = false;
    var body = '';

    req.on('data', function(data) {
        body += data;
    });

    req.on('end', function() {
        var postBody = qs.parse(body);

        if (postBody.cookie != null) {
            fetchAllGroups(req, res,db);
        } else if (postBody.userid != null) {
            if (postBody.option == "create") {
                createGroup(req, res, db,postBody.userid, postBody.groupname, "https://ryserver.herokuapp.com/upload?option=show&name="+postBody.groupname+"&size=82");
            } else if (postBody.option == "join") {
                joinInGroup(req, res, postBody.userid, postBody.groupid, postBody.groupname, db);
            } else if (postBody.option == "quit") {
                quitGroup(req, res, postBody.userid, postBody.groupid, db);
            } else if(postBody.option == "dismiss"){
                dismissGroup(req, res, postBody.userid, postBody.groupid, db)
            }else{
                fetchGroupByUser(req,res,db,postBody.userid, db);
            }
        } else {
            res.writeHead(403, {
                'Content-Type': 'text/plain',
                'Content-Length': "Missing parameter.".length
            });
            res.end("Missing parameter.");
            console.log("Missing parameter.");
            return;
        }
    })
}

function createGroup(req, res, db, userid, groupname, portrait) {
    db.get("select * from groups where groupname = ?", groupname, function(err, row) {
        if (err != null) {
            res.writeHead(500, {
                'Content-Type': 'text/plain',
                'Content-Length': "Server error".length
            });
            res.end("Server error");
            console.log(err);
        } else if (typeof row == "undefined" || row.length == 0) {
            var obj = new Object();
           var insert =  db.run("insert into groups (userid,groupname,portrait) values (?,?,?)",
                [userid,groupname,portrait],
                function(err, row, field) {
                    if (err==null) {
                        joinInGroup(req, res, userid, this.lastID, groupname, db)
                        obj.groupID = this.lastID;
                        obj.groupName = groupname;
                        obj.portrait = portrait;
                        obj.code = 200;
                        var responseString = JSON.stringify(obj);
                        res.writeHead(200, {
                            'Content-Type': 'text/plain',
                            'Content-Length': Buffer.byteLength(responseString, 'utf8')
                        });
                        res.end(responseString);
                    };
                });
        } else {
            res.writeHead(403, {
                'Content-Type': 'text/plain',
                'Content-Length': "Group already exist".length
            });
            res.end("Group already exist");
            console.log(row.id + " is already exist");
        }
    })
}

/*获取配置文件中的群组*/
function fetchAllGroups(req, res, db) {
    db.all("select * from groups", function(err, rows) {
        if (err != null) {
            res.writeHead(500, {
                'Content-Type': 'text/plain',
                'Content-Length': "Server error".length
            });
            res.end("Server error");
            console.log(err);
        } else if (typeof rows == "undefined") {
            res.writeHead(500, {
                'Content-Type': 'text/plain',
                'Content-Length': "Server Error.".length
            });
            res.end("Server Error.");
        } else {
            var responseString = JSON.stringify(rows);
            res.writeHead(200, {
                'Content-Type': 'text/plain',
                'Content-Length': Buffer.byteLength(responseString, 'utf8')
            });
            res.end(responseString);
        }
    });

    // var groups = require(path.join(source, 'groups.json'));
    // var responseString = JSON.stringify(groups);
    // res.writeHead(200, {
    //     'Content-Type': 'text/plain',
    //     'Content-Length': Buffer.byteLength(responseString, 'utf8')
    // });
    // res.end(responseString);
}

function fetchGroupByUser(req, res, db, userid) {
    db.all("select * from groups where id in (select groupid from useringroup where userid = ?)", userid, function(err, rows) {
        if (err != null) {
            res.writeHead(500, {
                'Content-Type': 'text/plain',
                'Content-Length': "Server error".length
            });
            res.end("Server error");
            console.log(err);
        } else if (typeof rows == "undefined") {
            res.writeHead(403, {
                'Content-Type': 'text/plain',
                'Content-Length': "User has no group.".length
            });
            res.end("User has no group.");
            console.log(userid + " has no group.");
        } else {
            var responseString = JSON.stringify(rows);
            res.writeHead(200, {
                'Content-Type': 'text/plain',
                'Content-Length': Buffer.byteLength(responseString, 'utf8')
            });
            res.end(responseString);
        }
    });
}

function fetchUserIdByGroup (argument) {
    
}

/*加入/创建群组*/
function joinInGroup(req, res, userid, groupid, groupname, db) { 
    // groupsActions("join", req, res, userid, groupid, groupname, db);
        db.get("select userid, groupid from useringroup where userid = ? and groupid = ?", [userid,groupid], function(err, row) {
        if (err != null) {
            res.writeHead(500, {
                "Content-Type": "text/plain",
                "Content-Length": "Server Error".length
            });
            res.end("Server Error");
            console.log(err);
        } else if (typeof(row) == 'undefined') {
                db.run("insert into useringroup (userid, groupid) values(?,?)", [userid, groupid], function (err, row) {
                    console.log(err)
                    if (err == null) {
                         res.writeHead(200,{'Content-Type': 'text/plain','Content-Length': "successful".length});
                        res.end("successful");
                    };}
                );
                res.writeHead(200,{'Content-Type': 'text/plain','Content-Length': "successful".length});
                res.end("successful");
        } else{
            res.writeHead(403,{'Content-Type': 'text/plain','Content-Length': "user already in group".length});
            res.end("User already in group");
            console.log(row.id + " is already in group");
        }
    });
}

/*退出群组*/
function quitGroup(req, res, userid, groupid,db) {
    console.log("Userid:"+userid+" ,groupid:"+groupid)
    // groupsActions("quit", req, res, userid, groupid, groupname, db);
    db.run("delete from useringroup where userid = ? and groupid = ?", [userid,groupid], function (err, row) {
        console.log(err)
        if (err == null) {
             res.writeHead(200,{'Content-Type': 'text/plain','Content-Length': "successful".length});
            res.end("successful");
        };
    });
}

/*解散群组*/
function dismissGroup(req, res, userid, groupid,db) {
    // groupsActions("dismiss", req, res, userid, groupid, groupname, db);
    db.get("select id from groups where userid = ?", userid, function(err, row){
        if (err != null) {
            res.writeHead(500, {
                "Content-Type": "text/plain",
                "Content-Length": "Server Error".length
            });
            res.end("Server Error");
            console.log(err);
        } else if (typeof(row) == 'undefined') {
            res.writeHead(403,{'Content-Type': 'text/plain','Content-Length': "group not belongs to user".length});
            res.end("group not belongs to user");
            console.log("group" + row.id + " not belongs to user");
        } else{
            quitGroup(req,res,userid,groupid, db);
            db.run("delete from groups where userid = ? and id = ?", [userid, groupid]);
             res.writeHead(200,{'Content-Type': 'text/plain','Content-Length': "successful".length});
            res.end("successful");
        }
    });
}

function groupsActions(option, req, res, userid, groupid, groupname, db) {
    console.log("option: "+option)
    var post_data = qs.stringify({
        "userId": userid,
        "groupId": groupid,
        "groupName": groupname
    });
    // var post_data = "userid="+userid+"&group["+groupid+"]="+groupname;
    var post_options = {
        host: conf.apiHost,
        port: conf.apiPort,
        method: "POST",
        headers: {
            "appKey": conf.appKey,
            "appSecret": conf.appSecret,
            "Content-Type": "Application/x-www-form-urlencoded",
            "Content-Length": Buffer.byteLength(post_data, 'utf8')
        }
    };

    db.get("select userid, groupid from useringroup where userid = ? and groupid = ?", [userid,groupid], function(err, row) {
        if (err != null) {
            res.writeHead(500, {
                "Content-Type": "text/plain",
                "Content-Length": "Server Error".length
            });
            res.end("Server Error");
            console.log(err);
        } else if (typeof(row) == 'undefined') {
            if (option == "join") {
                db.run("insert into useringroup (userid, groupid) values(?,?)", [userid, groupid]);
                post_options.path = "/group/join.json"
            } else {
                res.writeHead(406, {
                    "Content-Type": "text/plain",
                    "Content-Length": "User is not exist".length
                });
                res.end("User is not exist");
                console.log("User is not exist");
            }
        } else {
            switch (option) {
                case "quit":
                    post_options.path = "/group/quit.json";
                    db.run("delete from useringroup where userid = ?", userid);
                    break;
                case "dismiss":
                    post_options.path = "/group/dismiss.json";
                    db.run("delete from useringroup where groupid = ?", groupid);
                    de.run("delete from groups where id = ?", groupid);
                    break;
                default:
                    post_options.path = "/group/sync.json"
                    break;
            }
        }
    });

    var post_req = http.request(post_options, function(response) {
        console.log(post_data)
        console.log(post_options)
        req.finish = true;
        response.setEncoding('utf8');
        var responseString = '';
        response.on('data', function(chunk) {
            responseString += chunk;
        });

        response.on('end', function() {
            console.log(">>>>>>>>>>>>>>>>>>>>>>>")
            console.log("responseString: "+responseString)
            responseString = JSON.stringify(responseString);
            res.writeHead(response.statusCode, {
                "Content-Type": "text/plain",
                "Content-Length": Buffer.byteLength(responseString, 'utf8')
            });
            console.log(responseString);
             console.log("<<<<<<<<<<<<<<<<<<<<<<<")
            res.end(responseString)
        });
    });

    post_req.on('error', function(e) {
        req.finish = true;
        console.log("problem with request: " + e.message);
        res.writeHead(500, {
            "Content-Type": "text/plain",
            "Content-Length": e.message.length
        });
        req.end(e.message)
    });

    post_req.write(post_data);
    post_req.end();
}

function isGroupBelongsToUser (req, res, userid, groupid) {
    db.get("select * from useringroup where userid = ? and groupid = ?", [userid, groupid], function(err, rows){
         if (err != null){
            res.writeHead(500,{'Content-Type': 'text/plain','Content-Length': "Server error".length});
            res.end("Server error");
            console.log(err);
        }else if (typeof rows == "undefined"){
            res.writeHead(500,{'Content-Type': 'text/plain','Content-Length': "Server error".length});
            res.end("Server error");
            console.log(row);
        }else{
            var responseString = JSON.stringify(rows);
            res.writeHead(200,{'Content-Type': 'text/plain','Content-Length': Buffer.byteLength(responseString,'utf8')});
            res.end(responseString);
        }
    });
}

exports.process = process;